import { TypeOf } from './tools.js';

/**
 * 获取sessionStorage数据
 * @param {string} key 获取的key
 * @param {boolean} isLocal 是否从localStorage中获取
 * @returns
 */
export const GetStorage = ({ key, isLocal = false }) => {
  let storage;
  if (isLocal) {
    storage = localStorage.getItem(key) || '';
    const isBool = storage.includes('{') && storage.includes('}');
    return storage !== '' ? (isBool ? JSON.parse(storage) : storage) : false;
  } else {
    storage = sessionStorage.getItem(key) || '';
    const isBool = storage.includes('{') && storage.includes('}');
    return storage !== '' ? (isBool ? JSON.parse(storage) : storage) : false;
  }
};

/**
 * 保存数据到sessionStorage
 * @param {string} key 保存的key
 * @param {any} value 保存的数据
 * @param {boolean} isLocal 是否保存到localStorage
 * @returns
 */
export const SetStorage = ({ key, value, isLocal = false }) => {
  const obj = ['object', 'function', 'array', 'date', 'formData'];
  const result = obj.includes(TypeOf(value)) ? JSON.stringify(value) : value;
  if (isLocal) {
    localStorage.setItem(key, result);
  } else {
    sessionStorage.setItem(key, result);
  }
};

/**
 * 删除数据
 * @param {string} key
 * @param {boolean} isLocal
 */
export const RemoveStore = ({ key, isLocal = false }) => {
  if (isLocal) {
    localStorage.removeItem(key);
  } else {
    sessionStorage.removeItem(key);
  }
};
